﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;

namespace WebApp
{
    /// <summary>
    /// 
    /// </summary>
    public class Program
    {
        /// <summary>
        /// Main
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            var config = GetHostConfig();

            var logger = NLog.Web.NLogBuilder.ConfigureNLog($"Configs/nlog.{config["Server:EnvironmentName"]}.config").GetCurrentClassLogger();
            try
            {
                logger.Debug("init main");
                CreateHostBuilder(config, args).Build().Run();
            }
            catch (Exception exception)
            {
                //NLog: catch setup errors
                logger.Error(exception, "Stopped program because of exception");
                throw;
            }
            finally
            {
                // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
                NLog.LogManager.Shutdown();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="config"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static IHostBuilder CreateHostBuilder(IConfigurationRoot config, string[] args)
        {
            var host = Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder
                    .UseStartup<Startup>()
                    .UseEnvironment(config["Server:EnvironmentName"])
                    .UseUrls(config["Server:Urls"]);
                })
                 .ConfigureLogging(logging =>
                 {
                     //logging.ClearProviders();
                     if (config["Server:EnvironmentName"] == "Development")
                     {
                         logging.AddConsole();
                     }
                     logging.AddNLog($"Configs/nlog.{config["Server:EnvironmentName"]}.config");
                 })
                .UseNLog();  // NLog: Setup NLog for Dependency injection;
            return host;
        }

        /// <summary>
        /// 主要环境信息
        /// </summary>
        /// <returns></returns>
        public static IConfigurationRoot GetHostConfig()
        {
            return new ConfigurationBuilder()
               .SetBasePath(Environment.CurrentDirectory)
               .AddJsonFile("hosting.json", optional: true)
               .Build();
        }
    }
}
